import React, { useEffect, useState } from "react";
import { View, Text, Button } from "@tarojs/components";
import "./index.less";
import { LeftIcon, RightIcon } from "../Icons";

interface CalendarProps {
  stats?: {
    [key: string]: number;
  };
  onDateSelect?: (date: string) => void;
  onMonthChange?: (month: string) => void;
}

const getFormatDate = (year, month, day) =>
  `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;

const Calendar: React.FC<CalendarProps> = ({
  stats = {},
  onDateSelect,
  onMonthChange,
}) => {
  const mouth = new Date().getMonth() + 1;
  const year = new Date().getFullYear();
  const day = new Date().getDate();
  const [currentYear, setCurrentYear] = useState(year);
  const [currentMonth, setCurrentMonth] = useState(mouth);

  const today = getFormatDate(year, mouth, day);
  const [selectedDate, setSelectedDate] = useState<string>(today);

  const getDaysInMonth = () => {
    return new Date(currentYear, currentMonth - 1, 0).getDate();
  };

  const getFirstDayOfMonth = () => {
    return new Date(currentYear, currentMonth - 1, 1).getDay();
  };

  const handlePrevMonth = () => {
    let month = currentMonth;
    let year = currentYear;
    if (month === 1) {
      month = 12;
      year--;
    } else {
      month--;
    }
    setCurrentMonth(month);
    setCurrentYear(year);
    onMonthChange?.(`${year}-${String(month).padStart(2, "0")}`);
  };

  const handleNextMonth = () => {
    let month = currentMonth;
    let year = currentYear;

    if (month === 12) {
      month = 1;
      year++;
    } else {
      month++;
    }
    setCurrentMonth(month);
    setCurrentYear(year);
    onMonthChange?.(`${year}-${String(month).padStart(2, "0")}`);
  };

  useEffect(() => {
    onDateSelect?.(selectedDate);
    onMonthChange?.(selectedDate.slice(0, 7));
  }, []);

  const handleDateClick = (date: string) => {
    setSelectedDate(date);
    onDateSelect?.(date);
  };

  const renderCalendar = () => {
    const daysInMonth = getDaysInMonth();
    const firstDay = getFirstDayOfMonth();
    const calendarDays: JSX.Element[] = [];
    // Fill leading empty cells
    for (let i = 0; i < firstDay; i++) {
      calendarDays.push(
        <View key={`empty-${i}`} className="calendar-day empty" />
      );
    }

    // Fill actual days
    for (let day = 1; day <= daysInMonth; day++) {
      const dateStr = `${currentYear}-${String(currentMonth).padStart(
        2,
        "0"
      )}-${String(day).padStart(2, "0")}`;
      const isSelected = selectedDate === dateStr;

      // Calculate color intensity based on count
      let bgColor = "#f9f9f9";
      if (stats[dateStr]) {
        const opacity = Math.min(0.8, stats[dateStr] / 10);
        bgColor = `rgba(0, 150, 255, ${opacity})`;
      }

      calendarDays.push(
        <View
          key={`day-${day}`}
          className={`calendar-day ${isSelected ? "selected" : ""} ${
            dateStr === today ? "today" : ""
          }`}
          style={{ backgroundColor: bgColor }}
          onClick={() => handleDateClick(dateStr)}
        >
          <Text className="day-number">{day}</Text>
          {/* {stats[dateStr] && (
            <Text className="day-count">{stats[dateStr]}</Text>
          )} */}
        </View>
      );
    }

    return calendarDays;
  };

  return (
    <View className="calendar-container">
      <View className="calendar-header">
        <LeftIcon type="white" onClick={handlePrevMonth} size={1.4} />

        <Text className="month-year">
          {currentYear}年 {currentMonth}月
        </Text>
        <RightIcon type="white" onClick={handleNextMonth} size={1.4} />
      </View>

      <View className="calendar-weekdays">
        {["日", "一", "二", "三", "四", "五", "六"].map((day) => (
          <Text key={day} className="weekday">
            {day}
          </Text>
        ))}
      </View>

      <View className="calendar-grid">{renderCalendar()}</View>
    </View>
  );
};

export default Calendar;
